<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文章详情 - 智慧农业文章中心</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.8;
            color: #333;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
        }

        .back-button {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: rgba(255,255,255,0.1);
            color: white;
            text-decoration: none;
            padding: 12px 20px;
            border-radius: 25px;
            margin-bottom: 30px;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
            font-weight: 500;
        }

        .back-button:hover {
            background: rgba(255,255,255,0.2);
            transform: translateX(-3px);
        }

        .back-button::before {
            content: '←';
            font-size: 1.2rem;
            transition: transform 0.3s ease;
        }

        .back-button:hover::before {
            transform: translateX(-3px);
        }

        .article-container {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.1);
            position: relative;
            overflow: hidden;
        }

        .article-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 6px;
            background: linear-gradient(90deg, #667eea, #764ba2);
        }

        .loading {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .loading-spinner {
            display: inline-block;
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .article-meta {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }

        .article-id {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: 600;
        }

        .article-category {
            background: #e8f4fd;
            color: #1976d2;
            padding: 6px 12px;
            border-radius: 15px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .article-title {
            font-size: 2.2rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 30px;
            line-height: 1.3;
        }

        .article-content {
            font-size: 1.1rem;
            line-height: 1.8;
            color: #444;
            text-align: justify;
            margin-bottom: 40px;
        }

        .article-content p {
            margin-bottom: 20px;
        }

        .article-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-top: 30px;
            border-top: 2px solid #f0f0f0;
            flex-wrap: wrap;
            gap: 15px;
        }

        .action-buttons {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .action-btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            border-radius: 25px;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
            border: none;
            cursor: pointer;
            font-size: 0.95rem;
        }

        .primary-btn {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }

        .primary-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
        }

        .secondary-btn {
            background: #f8f9fa;
            color: #666;
            border: 2px solid #e9ecef;
        }

        .secondary-btn:hover {
            background: #e9ecef;
            color: #333;
        }

        .share-info {
            color: #666;
            font-size: 0.9rem;
        }

        .error-message {
            background: #ff6b6b;
            color: white;
            padding: 30px;
            border-radius: 15px;
            text-align: center;
            margin: 20px 0;
        }

        .error-message h3 {
            margin-bottom: 15px;
            font-size: 1.3rem;
        }

        .error-message p {
            margin-bottom: 20px;
            opacity: 0.9;
        }

        .retry-btn {
            background: white;
            color: #ff6b6b;
            border: none;
            padding: 12px 24px;
            border-radius: 25px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .retry-btn:hover {
            background: #f8f9fa;
            transform: translateY(-2px);
        }

        .reading-progress {
            position: fixed;
            top: 0;
            left: 0;
            width: 0%;
            height: 4px;
            background: linear-gradient(90deg, #667eea, #764ba2);
            z-index: 1000;
            transition: width 0.3s ease;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }

            .article-container {
                padding: 25px;
                border-radius: 15px;
            }

            .article-title {
                font-size: 1.8rem;
            }

            .article-content {
                font-size: 1rem;
            }

            .article-actions {
                flex-direction: column;
                align-items: stretch;
            }

            .action-buttons {
                justify-content: center;
            }

            .share-info {
                text-align: center;
            }
        }

        @media (max-width: 480px) {
            .article-title {
                font-size: 1.5rem;
            }

            .article-meta {
                justify-content: center;
            }

            .action-buttons {
                flex-direction: column;
            }

            .action-btn {
                justify-content: center;
            }
        }

        /* 打印样式 */
        @media print {
            body {
                background: white;
            }

            .back-button,
            .article-actions,
            .reading-progress {
                display: none;
            }

            .article-container {
                box-shadow: none;
                padding: 20px 0;
            }
        }
    </style>
</head>
<body>
    <div class="reading-progress" id="readingProgress"></div>
    
    <div class="container">
        <a href="articles.html" class="back-button">
            返回文章列表
        </a>

        <div class="article-container">
            <div class="loading" id="loading">
                <div class="loading-spinner"></div>
                <p>正在加载文章内容...</p>
            </div>

            <div class="error-message" id="error" style="display: none;">
                <h3>加载失败</h3>
                <p id="errorMessage">无法获取文章内容，请检查网络连接</p>
                <button class="retry-btn" onclick="loadArticle()">重新加载</button>
            </div>

            <article id="articleContent" style="display: none;">
                <div class="article-meta">
                    <span class="article-id" id="articleId">文章 #1</span>
                    <span class="article-category">智慧农业</span>
                </div>

                <h1 class="article-title" id="articleTitle"></h1>
                
                <div class="article-content" id="articleBody"></div>

                <div class="article-actions">
                    <div class="action-buttons">
                        <button class="action-btn primary-btn" onclick="shareArticle()">
                            📤 分享文章
                        </button>
                        <button class="action-btn secondary-btn" onclick="printArticle()">
                            🖨️ 打印文章
                        </button>
                    </div>
                    <div class="share-info">
                        <span>📖 阅读时长约 <span id="readingTime">3</span> 分钟</span>
                    </div>
                </div>
            </article>
        </div>
    </div>

    <script>
        let currentArticle = null;

        function getArticleId() {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get('id');
        }

        function showLoading() {
            document.getElementById('loading').style.display = 'block';
            document.getElementById('error').style.display = 'none';
            document.getElementById('articleContent').style.display = 'none';
        }

        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
        }

        function showError(message = '无法获取文章内容，请检查网络连接') {
            document.getElementById('error').style.display = 'block';
            document.getElementById('errorMessage').textContent = message;
            hideLoading();
        }

        function showArticle(article) {
            document.getElementById('articleContent').style.display = 'block';
            hideLoading();
        }

        function calculateReadingTime(text) {
            const wordsPerMinute = 200; // 中文阅读速度约200字/分钟
            const wordCount = text.length;
            const minutes = Math.ceil(wordCount / wordsPerMinute);
            return Math.max(1, minutes);
        }

        function formatContent(content) {
            // 将长文本分段显示
            const sentences = content.split('。');
            const paragraphs = [];
            let currentParagraph = '';
            
            sentences.forEach((sentence, index) => {
                if (sentence.trim()) {
                    currentParagraph += sentence + '。';
                    // 每3-4句话分一段
                    if ((index + 1) % 3 === 0 || index === sentences.length - 1) {
                        if (currentParagraph.trim()) {
                            paragraphs.push(`<p>${currentParagraph.trim()}</p>`);
                            currentParagraph = '';
                        }
                    }
                }
            });
            
            return paragraphs.join('');
        }

        function renderArticle(article) {
            currentArticle = article;
            
            // 更新页面标题
            document.title = `${article.title} - 智慧农业文章中心`;
            
            // 填充文章内容
            document.getElementById('articleId').textContent = `文章 #${article.id}`;
            document.getElementById('articleTitle').textContent = article.title;
            document.getElementById('articleBody').innerHTML = formatContent(article.content);
            
            // 计算阅读时间
            const readingTime = calculateReadingTime(article.content);
            document.getElementById('readingTime').textContent = readingTime;
            
            showArticle(article);
            
            // 添加入场动画
            const articleElement = document.getElementById('articleContent');
            articleElement.style.opacity = '0';
            articleElement.style.transform = 'translateY(20px)';
            
            requestAnimationFrame(() => {
                articleElement.style.transition = 'all 0.6s ease';
                articleElement.style.opacity = '1';
                articleElement.style.transform = 'translateY(0)';
            });
        }

        async function loadArticle() {
            const articleId = getArticleId();
            
            if (!articleId) {
                showError('缺少文章ID参数');
                return;
            }

            showLoading();

            try {
                const response = await fetch(`/api/articleDetail?id=${articleId}`);
                
                if (!response.ok) {
                    if (response.status === 404) {
                        throw new Error('文章不存在');
                    } else if (response.status === 400) {
                        throw new Error('无效的文章ID');
                    } else {
                        throw new Error(`服务器错误 (${response.status})`);
                    }
                }
                
                const article = await response.json();
                
                if (article && article.title && article.content) {
                    renderArticle(article);
                } else {
                    throw new Error('文章数据格式错误');
                }
                
            } catch (error) {
                console.error('加载文章失败:', error);
                showError(error.message);
            }
        }

        function shareArticle() {
            if (!currentArticle) return;
            
            if (navigator.share) {
                navigator.share({
                    title: currentArticle.title,
                    text: currentArticle.content.substring(0, 100) + '...',
                    url: window.location.href
                }).catch(console.error);
            } else {
                // 复制链接到剪贴板
                navigator.clipboard.writeText(window.location.href).then(() => {
                    alert('文章链接已复制到剪贴板！');
                }).catch(() => {
                    alert('分享功能暂不可用');
                });
            }
        }

        function printArticle() {
            window.print();
        }

        // 阅读进度条
        function updateReadingProgress() {
            const article = document.getElementById('articleContent');
            if (!article || article.style.display === 'none') return;
            
            const scrollTop = window.pageYOffset;
            const docHeight = document.body.scrollHeight - window.innerHeight;
            const scrollPercent = (scrollTop / docHeight) * 100;
            
            document.getElementById('readingProgress').style.width = Math.min(100, Math.max(0, scrollPercent)) + '%';
        }

        // 页面加载完成后自动加载文章
        document.addEventListener('DOMContentLoaded', loadArticle);

        // 监听滚动事件更新阅读进度
        window.addEventListener('scroll', updateReadingProgress);

        // 键盘快捷键
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                window.location.href = 'articles.html';
            } else if (e.key === 'r' || e.key === 'R') {
                if (e.ctrlKey || e.metaKey) {
                    e.preventDefault();
                    loadArticle();
                }
            } else if (e.key === 'p' || e.key === 'P') {
                if (e.ctrlKey || e.metaKey) {
                    e.preventDefault();
                    printArticle();
                }
            }
        });
    </script>
</body>
</html>
